package com.bestcem.xm.qdes.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bestcem.xm.common.core.annotation.XmGet;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.common.core.exception.BusinessException;
import com.bestcem.xm.component.mybatis.base.ResultPage;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.component.security.dto.TokenDTO;
import com.bestcem.xm.qdes.controller.param.ProjectLibCreateParam;
import com.bestcem.xm.qdes.controller.param.ProjectLibDuplicateParam;
import com.bestcem.xm.qdes.controller.param.ProjectLibPageParam;
import com.bestcem.xm.qdes.controller.param.ProjectLibUpdateParam;
import com.bestcem.xm.qdes.controller.vo.OnlyIdVo;
import com.bestcem.xm.qdes.controller.vo.QdesLibProjectVo;
import com.bestcem.xm.qdes.controller.vo.QdesLibprojectLabelListVo;
import com.bestcem.xm.qdes.controller.vo.QdesLibprojectUserVo;
import com.bestcem.xm.qdes.entity.QdesProject;
import com.bestcem.xm.qdes.enums.LibTopicTypeEnum;
import com.bestcem.xm.qdes.service.QdesLibProjectService;
import com.bestcem.xm.qdes.util.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * @author guitao.lu
 * @version V1.0
 * @date 2022/8/1
 */
@Slf4j
@Api(tags = "模板库-问卷库")
@RestController
@RequiredArgsConstructor
@RequestMapping("/qdes/libprojects")
public class ProjectLibController {
    private static final String OFFICIAL = "official";

    private @NonNull QdesLibProjectService libprojectService;

    @ApiImplicitParams({
            @ApiImplicitParam(required = true, paramType = "path", dataTypeClass = String.class, name = "url", value = "url", allowableValues = "industry,official"),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "page", value = "页码"),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "rowsPerPage", value = "每页条数")
    })
    @ApiOperation(value = "问卷库获取接口")
    @GetMapping({"/{url:industry|official}"})
    public XmResultJson<Object> pageProjectLib(@PathVariable("url") String url, @ApiIgnore Page<?> page, @XmGet ProjectLibPageParam pageParam,
                                               HttpServletRequest request) {
        log.info("Now to pageProjectLib");
        pageParam.setIsOfficial(url.contains(OFFICIAL));
        // 如果是企业库且页数为空时返回所有
        //相同地址，存在不带分页的请求
        if (!PageUtil.isPageQuery(request)) {
            return XmResultJson.success(libprojectService.getAllIndustryProject(pageParam));
        }
        page = libprojectService.pageLibproject(page, pageParam);
        //转换返回结构
        ResultPage<?> data = PageUtil.getResultPage(page.getCurrent(), page.getTotal(), page.getRecords());
        return XmResultJson.success(data);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(required = true, paramType = "path", dataTypeClass = String.class, name = "id", value = "id")
    })
    @ApiOperation(value = "问卷库获取单个问卷详情接口")
    @GetMapping({"/industry/{id:[a-fA-F0-9]{24}}"})
    public XmResultJson<QdesLibProjectVo> getProjectLib(@PathVariable("id") String id) {
        log.info("Now to pageProjectLib");
        QdesLibProjectVo libprojectVo = libprojectService.getOneIndustryById(id, SecurityContextHolder.getOrgId());
        //转换返回结构
        return XmResultJson.success(libprojectVo);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(required = true, paramType = "path", dataTypeClass = String.class, name = "url", value = "url", allowableValues = "project,official")
    })
    @ApiOperation(value = "问卷库创建接口")
    @PostMapping({"/{url:project|official}"})
    public XmResultJson<OnlyIdVo> createProjectLib(@PathVariable("url") String url, @RequestBody @Validated ProjectLibCreateParam param) {
        log.info("Now to CreateProjectLib");
        param.setUserId(SecurityContextHolder.getUserId());
        param.setOrgId(SecurityContextHolder.getOrgId());
        param.setIsOfficial(url.contains(OFFICIAL));
        OnlyIdVo dbResult;
        try {
            dbResult = libprojectService.createLibProject(param);
        } catch (IOException e) {
            return XmResultJson.fail(1, e.getMessage());
        }
        return XmResultJson.success(dbResult);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(required = true, paramType = "path", dataTypeClass = String.class, name = "url", value = "url", allowableValues = "industry,official"),
            @ApiImplicitParam(required = true, paramType = "path", dataTypeClass = String.class, name = "id", value = "id")
    })
    @ApiOperation(value = "问卷库修改接口")
    @PutMapping({"/{url:industry|official}/{id:[a-fA-F0-9]{24}}"})
    public XmResultJson<OnlyIdVo> updateProjectLib(@PathVariable("url") String url, @PathVariable("id") String id, @RequestBody ProjectLibUpdateParam param) {
        log.info("Now to UpdateProjectLib");
        param.setUserId(SecurityContextHolder.getUserId());
        param.setOrgId(SecurityContextHolder.getOrgId());
        TokenDTO tokenDTO = SecurityContextHolder.getToken();
        param.setIsOfficial(url.contains(OFFICIAL));
        if (param.getLike() != null) {
            param.setLibType(LibTopicTypeEnum.LIBTOPIC_LIB_TYPE_FAVORITE.getValue());
        }
        OnlyIdVo dbResult = libprojectService.updateLibProject(param, id, tokenDTO);
        return XmResultJson.success(dbResult);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(required = true, paramType = "path", dataTypeClass = String.class, name = "url", value = "url", allowableValues = "industry,official"),
            @ApiImplicitParam(required = true, paramType = "path", dataTypeClass = String.class, name = "id", value = "id")
    })
    @ApiOperation(value = "问卷库删除接口")
    @DeleteMapping({"/{url:industry|official}/{id:[a-fA-F0-9]{24}}"})
    public XmResultJson<Void> deleteProjectLib(@PathVariable("id") String id, @PathVariable("url") String url) {
        log.info("Now to DeleteProjectLib");
        TokenDTO tokenDTO = SecurityContextHolder.getToken();
        libprojectService.deleteLibProject(id, tokenDTO);
        return XmResultJson.success();
    }

    @ApiOperation(value = "复制问卷库")
    @PostMapping("/duplicate/{id:[a-fA-F0-9]{24}}")
    public XmResultJson<OnlyIdVo> duplicateProjectLib(@PathVariable("id") String id, @RequestBody @Validated ProjectLibDuplicateParam param) {
        log.info("Now to DuplicateProjectLib");
        if (StringUtils.isEmpty(id)) {
            throw new BusinessException("id值不能为空");
        }
        param.setUserId(SecurityContextHolder.getUserId());
        param.setOrgId(SecurityContextHolder.getOrgId());
        param.setId(id);
        return XmResultJson.success(libprojectService.duplicateProjectLib(param));
    }

    @ApiOperation(value = "获取问卷库创建人信息")
    @GetMapping("/industry/user")
    public XmResultJson<List<QdesLibprojectUserVo>> getProjectLibUser() {
        log.info("Now to getProjectLibUser");
        //转换返回结构
        return XmResultJson.success(libprojectService.getProjectLibUser(SecurityContextHolder.getOrgId()));
    }

    @ApiOperation(value = "获取公共库的标签")
    @GetMapping("/official/label")
    public XmResultJson<QdesLibprojectLabelListVo> getProjectLibLabel() {
        log.info("Now to getProjectLibLabel");
        //转换返回结构
        return XmResultJson.success(libprojectService.getProjectLibLabel());
    }

    @ApiImplicitParams({
            @ApiImplicitParam(required = true, paramType = "path", dataTypeClass = String.class, name = "id", value = "id")
    })
    @ApiOperation(value = "引用模版库创建问卷")
    @PostMapping({"/qstruct/{id:[a-fA-F0-9]{24}}"})
    public XmResultJson<QdesProject> useProjectTemp(@PathVariable("id") String id, @RequestBody JSONObject param) {
        log.info("Now to useProjectTemp");
        QdesProject ret;
        try {
            ret = libprojectService.useProjectTemp(id, SecurityContextHolder.getUserId(),
                    SecurityContextHolder.getOrgId(), param);
        } catch (IOException e) {
            return XmResultJson.fail(1, e.getMessage());
        }
        return XmResultJson.success(ret);
    }
}
